package cn.itcast.comsumer.controller;

import cn.itcast.comsumer.client.UserClient;
import cn.itcast.comsumer.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.stream.Stream;

@RestController
@RequestMapping("consumer")
/*@DefaultProperties(defaultFallback = "queryBuIdFallBack")*/
public class ConsumerController {

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        return userClient.queryById(id);
    }

    /*@Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;*/

    /*@GetMapping("{id}")
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000")
    })
    public String queryById(@PathVariable("id")Long id){
        if (id == 1){
            throw new RuntimeException("太忙了");
        }
        String url = String.format("http://user-service/user/"+id);
        String user = restTemplate.getForObject(url, String.class);
        return user;
    }

    public String queryBuIdFallBack(){
        return "对不起，网络太拥挤了！";
    }*/
    /*@GetMapping("{id}")
    public User queryById(@PathVariable("id")Long id){
        String url = String.format("http://user-service/user/"+id);
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }*/

    /*@GetMapping("{id}")
    public User queryById(@PathVariable("id")Long id){
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        ServiceInstance instance = instances.get(0);
        String host = instance.getHost();
        int port = instance.getPort();
        String url = String.format("http://%s:%d/user/%d",host,port,id);
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }*/

}
